# 读取波士顿房价数据集
# 保存数据到文件
def work_1():
    from cProfile import label
    import pandas as pd
    import os
    # 
    path = os.path.join(os.getcwd(), 'what', 'boston.csv') #os.getcwd()获取当前工作目录
    col_names = ['CRIM', 'ZN', 'INDUS', 'CHAS',
    'NOX','RM', 'AGE',
    'DIS', 'RAD', 'TAX', 'PTRATIO', 'B',
    'LSTAT', 'MEDV']
    print(path)
    # 读取数据,用空格分割列
    df = pd.read_csv(path, names = col_names, sep='\s+')

    # 查看数据前行100行
    print(df.head(100)) # 可得数据是没有列名的
    print(df.describe())
    # 绘制MEDV?
    # 两张折线图
    import matplotlib.pyplot as plt
    plt.plot(df['MEDV'],label="MEDV")
    plt.plot(df['CRIM'],label="CRIM")
    # 如何写中文标题
    # .rc支持中文和.title写标题
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.title('MEDV和CRIM的折线图')
    # 如和添加轴线标签
    plt.xlabel('x_axis')
    plt.ylabel('y_axis')
    # 如何显示线条图例？.legend() 图例内展示的是什么？绘图函数中的label参数
    plt.legend()
    plt.show()

def work2():
    """
    Args:
        接受一组键盘输入的宽,高，及图片路径。
    Return:
        截取为该给定（宽，高）的图片
    """
    # 图片路径用什么读取？os.path.join()使其能够跨平台兼容
    import os 
    # img_path = os.path.join(os.getcwd(),"what","1.jpg")
    img_path = "1.jpg"
    # opencv 读取该图片：imgread()
    import cv2
    img = cv2.imread(img_path,cv2.IMREAD_COLOR)
    # # 检查图像是否成功加载
    if img is None:
        print(f"错误：无法加载图像，请检查路径是否正确: {img_path}")
        return
    
    # 显示图片
    cv2.imshow("originimg",img)
    print("按任意键继续...")
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    # 接受一个组参数
    try:
        hw_input = input("请输入宽高并用空格分割: ").split()
        # 限制数组大小
        assert len(hw_input) == 2, "请输入宽高两个数值"
        # 转换为整数并检查取值是否大于0
        width, height = int(hw_input[0]), int(hw_input[1])
        assert width > 0 and height > 0, "宽度和高度必须大于0"
        # 在终端打印图片原始大小
        print("原始图片尺寸:", img.shape)
        # 在终端打印挑战后大小
        print("调整后长度:", width)
        print("调整后宽度:", height)

        # 直接索引切片
        resized_img = img[0:height, 0:width]
        cv2.imshow("img月饼", resized_img)
        print("按任意键关闭窗口...")
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    except ValueError:
        print("错误：请输入有效的数字")
    except AssertionError as e:
        print(f"输入错误: {e}")
def work_3():
    #     k = cv2.waitKey(1000)
    #     if k == ord('q'):
    #         break
    #     cv2.destroyAllWindows()
    import os
    import cv2

    face_clf = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    path_big = './face_img'
    path_small = './small_face'
    foldlist = os.listdir(path_big)
    print(foldlist)
    for foldname in foldlist:
        path_big_sub = os.path.join(path_big, foldname)
        path_small_sub = os.path.join(path_small, foldname)
        # 检查该文件夹是否存在,并打印该路径，否则创建
        if os.path.exists(path_small_sub):
            print(path_small_sub)
            continue
        else:
            os.makedirs(path_small_sub)
            print(path_small_sub)

        img = cv2.imread(path_big_sub, flags=1)
        faces = face_clf.detectMultiScale(img, scaleFactor=1.3, minNeighbors=5)
        for x, y, w, h in faces:
            roi = img[y:y+h, x:x+w]  # 截取人脸部分
            cv2.imshow('', roi)
            cv2.imwrite(f'{path_small_sub}.jpg', roi)
            k = cv2.waitKey(1000)
            if k == ord('q'):
                break
        cv2.destroyAllWindows()

if __name__ == "__main__":
    # work_1()
    work_3()
